<template>
  <a-modal
    v-model:open="visible"
    title="创建知识库"
    :width="600"
    :confirm-loading="isSubmitting"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="create-knowledge-form">
      <!-- 知识库名称 -->
      <div class="form-item">
        <label class="form-label">
          知识库名称 <span class="required">*</span>
        </label>
        <a-input
          v-model:value="formData.name"
          placeholder="请输入知识库名称，如：角色A的背景设定"
          size="large"
        />
      </div>

      <!-- 知识库描述 -->
      <div class="form-item">
        <label class="form-label">
          知识库描述 <span class="optional">(可选)</span>
        </label>
        <a-textarea
          v-model:value="formData.description"
          placeholder="请简要描述知识库的内容，如角色的性格特点、背景故事、技能设定等..."
          :rows="3"
          show-count
          :maxlength="500"
        />
      </div>

      <!-- 文件上传区域 -->
      <div class="form-item">
        <label class="form-label">
          知识库文档 <span class="required">*</span>
        </label>

        <!-- 未上传文件时显示上传区域 -->
        <div v-if="!uploadedFile" class="upload-area">
          <a-upload-dragger
            :custom-request="handleFileUpload"
            :before-upload="beforeUpload"
            :show-upload-list="false"
            accept=".txt,.pdf,.doc,.docx"
          >
            <p class="ant-upload-drag-icon">
              <FileTextOutlined style="font-size: 48px; color: #1890ff;" />
            </p>
            <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
            <p class="ant-upload-hint">
              支持 .txt、.pdf、.doc、.docx 格式，文件大小不超过 1MB
            </p>
          </a-upload-dragger>


        </div>

        <!-- 已上传文件显示 -->
        <div v-else class="uploaded-file">
          <div class="file-info">
            <FileTextOutlined class="file-icon" />
            <div class="file-details">
              <div class="file-name">{{ uploadedFile.name }}</div>
              <div class="file-size">
                ({{ (uploadedFile.size / 1024).toFixed(1) }} KB)
              </div>
            </div>
            <a-button @click="removeFile" size="small">重新选择</a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      id="knowledge-file-input"
      type="file"
      accept=".txt,.pdf,.doc,.docx"
      style="display: none"
      @change="handleFileSelect"
    />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined, FileTextOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { CreateKnowledgeBaseRequest } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores/modules/auth'

// Props
interface Props {
  open: boolean
}

// Emits
interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const visible = ref(false)
const isSubmitting = ref(false)
const isProcessingFile = ref(false)
const uploadedFile = ref<File | null>(null)
const uploadedFileUrl = ref('')

const formData = ref({
  name: '',
  description: ''
})

// Store
const authStore = useAuthStore()

// API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top'
})



// 监听props变化
watch(() => props.open, (newVal) => {
  visible.value = newVal
})

watch(visible, (newVal) => {
  emit('update:open', newVal)
  if (!newVal) {
    resetForm()
  }
})

// 文件上传相关方法
const beforeUpload = (file: File) => {
  const allowedTypes = [
    'text/plain',
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ]
  const allowedExtensions = ['.txt', '.pdf', '.doc', '.docx']

  const isValidType = allowedTypes.includes(file.type) ||
    allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext))

  if (!isValidType) {
    message.error('只能上传 .txt、.pdf、.doc、.docx 格式的文件！')
    return false
  }
  const isLt1M = file.size / 1024 / 1024 < 1
  if (!isLt1M) {
    message.error('文件大小不能超过 1MB！')
    return false
  }
  return true
}

const handleFileUpload: UploadProps['customRequest'] = async (options) => {
  const { file, onSuccess, onError } = options
  if (file instanceof File) {
    isProcessingFile.value = true

    try {
      const formData = new FormData()
      formData.append('file', file)

      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        uploadedFile.value = file
        uploadedFileUrl.value = response.data.data
        message.success('文件上传成功！')
        onSuccess?.(response.data.data)
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      message.error('文件上传失败，请重试')
      onError?.(error as Error)
    } finally {
      isProcessingFile.value = false
    }
  }
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    if (!beforeUpload(file)) return

    isProcessingFile.value = true

    try {
      // 设置Authorization header
      const headers: Record<string, string> = {}
      if (authStore.token) {
        headers['Authorization'] = `Bearer ${authStore.token}`
      }

      const response = await api.uploadFile({ file }, {
        headers
      })

      if (response.data?.code === 0 && response.data?.data) {
        uploadedFile.value = file
        uploadedFileUrl.value = response.data.data
        message.success('文件选择成功！')
      } else {
        throw new Error('上传失败')
      }
    } catch (error) {
      console.error('文件上传失败:', error)
      message.error('文件上传失败，请重试')
    } finally {
      isProcessingFile.value = false
    }
  }
}

const handleFileInputClick = () => {
  const fileInput = document.getElementById('knowledge-file-input') as HTMLInputElement
  if (fileInput) {
    fileInput.click()
  }
}

const removeFile = () => {
  uploadedFile.value = null
  uploadedFileUrl.value = ''
  message.info('文件已移除')
}

// 表单提交
const handleSubmit = async () => {
  if (!formData.value.name.trim()) {
    message.warning('请输入知识库名称')
    return
  }

  if (!uploadedFileUrl.value) {
    message.warning('请上传知识库文档')
    return
  }

  isSubmitting.value = true
  try {
    // 准备创建知识库的请求数据
    const createKnowledgeBaseData: CreateKnowledgeBaseRequest = {
      fileUrl: uploadedFileUrl.value,
      name: formData.value.name,
      description: formData.value.description
    }

    // 设置Authorization header
    const headers: Record<string, string> = {}
    if (authStore.token) {
      headers['Authorization'] = `Bearer ${authStore.token}`
    }

    // 调用创建知识库接口
    const response = await api.createKnowledgeBase(createKnowledgeBaseData, {
      headers
    })

    if (response.data?.code === 0) {
      message.success('知识库创建成功！')
      console.log('知识库创建成功，响应数据:', response.data.data)

      // 触发成功事件
      emit('success')

      // 关闭弹窗
      visible.value = false
    } else {
      throw new Error(response.data?.message || '创建失败')
    }
  } catch (error) {
    console.error('创建知识库失败:', error)
    message.error('知识库创建失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  visible.value = false
}

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    description: ''
  }
  uploadedFile.value = null
  uploadedFileUrl.value = ''
  isSubmitting.value = false
  isProcessingFile.value = false
}
</script>

<style scoped>
.create-knowledge-form {
  padding: 16px 0;
}

.form-item {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #262626;
}

.required {
  color: #ff4d4f;
}

.optional {
  color: #8c8c8c;
  font-weight: normal;
}

.upload-area {

  padding: 16px;
  text-align: center;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #1890ff;
}

.upload-buttons {
  margin-top: 16px;
}

.uploaded-file {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  padding: 16px;
  background: #fafafa;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-icon {
  font-size: 24px;
  color: #1890ff;
  margin-right: 12px;
}

.file-details {
  flex: 1;
}

.file-name {
  font-weight: 600;
  color: #262626;
  margin-bottom: 4px;
}

.file-size {
  font-size: 12px;
  color: #8c8c8c;
}

:deep(.ant-upload-drag) {
  background: #fafafa !important;
}

:deep(.ant-upload-drag:hover) {
  border-color: #1890ff !important;
}

:deep(.ant-upload-drag.ant-upload-drag-hover) {
  border-color: #1890ff !important;
}
</style>
